
import { assetsDB } from '@/indexDB/index'
import { HOLD_LIST_KEY } from '@/views/hold/model'
import { DEFAULT_HOLD_LIST } from '@/views/hold/defaultHoldList'

import { platformList } from '@/indexDB/initPlatform'
import { strategyList } from '@/indexDB/initStrategy'
import { categoryList } from '@/indexDB/initCategory'


import type { HoldType } from '@/views/hold/model'
import { ref } from 'vue'

export interface HoldItem {
  id: string | number
  name: string
  code?: string
  type: HoldType
  strategy?: string
  strategyId: string | number
  strategyName?: string
  platform?: string
  platformId: string | number
  platformName?: string
  category?: string[]
  categoryId: string | number
  categoryName?: string
  holdNum: number
  holdPrice: number
  createTime: string
  updateTime: string
  latestPrice: number // 现价
  priceTime: string // 现价更新时间
  riseAndFall?: string | number // 涨跌幅
  holdValue: number // 持仓市值
  holdEarnings: number // 持仓收益
  holdEarningsPercent: string // 持仓收益率,百分比
}

export const holdList = ref<HoldItem[]>([])

export const initHoldDB = async () => {

  const arr = await assetsDB.holdList.toArray()
  if (!arr.length) {

    const listStr = localStorage.getItem(HOLD_LIST_KEY)
    const list: HoldItem[] = listStr ? JSON.parse(listStr) : DEFAULT_HOLD_LIST
    const finalList = list.map(holdItem => {
      const { platform, strategy, category } = holdItem
      const platformItem = platformList.value.find(each => each.code === platform)
      const strategyItem = strategyList.value.find(each => each.code === strategy)
      const lastCategoryCode = category?.pop()
      const categoryItem = categoryList.value.find(each => each.code === lastCategoryCode)

      return {
        ...holdItem,
        platformId: platformItem?.id ?? +new Date(),
        strategyId: strategyItem?.id ?? +new Date(),
        categoryId: categoryItem?.id ?? +new Date()
      }
    })

    await assetsDB.holdList.bulkPut(finalList)
    updateHoldList()
  } else {
    updateHoldList()
  }
}

export const updateHoldList = async () => {
  holdList.value = await assetsDB.holdList.toArray()
  return Promise.resolve(holdList.value)
}